<template>
  <div class="app-container home">
    <el-row :gutter="30" style="display: flex; align-items: center; justify-content: center;">
      <el-col :span="8" style="display: flex; justify-content: center; align-items: center; height: 400px;">
        <div></div>
        <div ref="standardchart" style="height: 100%; width: 100%; display: flex; justify-content: center; align-items: center;"/>
      </el-col>
      <el-col :span="16"  >
        <el-row :gutter="20" style="flex: 1; display: flex; flex-wrap: wrap;">
          <el-col :span="10" style="height:160px; display:flex; flex-direction: column; justify-content: center;">
            <div class="statistic-box">
              <div class="content" style="width: 100%">
                <div class="title">
                  <svg-icon icon-class="dashboard"/>
                  <span>现有指标体系数</span>
                  <div class="number">{{IndicatorSystemCount}}</div>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="10" style="height:160px; display:flex; flex-direction: column; justify-content: center;">
            <div class="statistic-box">
              <div class="content" style="width: 100%">
                <div class="title">
                  <svg-icon icon-class="user"/>
                  <span>累计访问数</span>
                  <div class="number">{{successfulLoginCount}}</div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10" style="height:160px; display:flex; flex-direction: column; justify-content: center; margin-top: 20px;">
            <div class="statistic-box">
              <div class="content" style="width: 100%">
                <div class="title">
                  <svg-icon icon-class="dashboard"/>
                  <span>参与评价标准数</span>
                  <div class="number">{{UD_dialog.standardCodeList.length}}</div>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="10" style="height:160px; display:flex; flex-direction: column; justify-content: center;margin-top: 20px;">
            <div class="statistic-box">
              <div class="content" style="width: 100%">
                <div class="title">
                  <svg-icon icon-class="user"/>
                  <span>标准总评价次数</span>
                  <div class="number">{{standardEvaluateCount}}</div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>

      </el-col>

    </el-row>

    <el-row>
      <el-table v-loading="loading" :data="dataList" >
        <el-table-column align="center" label="标准数据管理">
          <el-table-column label="序号" align="center" prop="id" width="100px" />
          <el-table-column label="数据名称" align="center" prop="dataName" :show-overflow-tooltip="true" width="150px" />
          <el-table-column label="标准号" align="center" prop="standardCode" :show-overflow-tooltip="true" width="150px" />
          <el-table-column label="状态" align="center" prop="status" width="150px">
            <template slot-scope="scope">
              <el-tag :type="statusTagMap[scope.row.status]">{{ statusMap[scope.row.status] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" width="150px" />
          <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:dataFile:edit']"
              >修改</el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="handleDownload(scope.row)"
                v-hasPermi="['system:dataFile:download']"
              >下载</el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-time"
                @click="handlePath(scope.row)"
                v-hasPermi="['system:dataFile:trace']"
              >跟踪</el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-s-operation"
                @click="handleCheck(scope.row)"
                v-hasPermi="['system:dataFile:audit']"
              >审核</el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:dataFile:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getDataList"
      />
    </el-row>


    <div style="margin-top: 20px;">
      <!-- 上传数据 ---------------------------->
      <el-button
        size="medium"
        type="primary"
        icon="el-icon-upload"
        @click="clickUpload()"
        v-hasPermi="['system:dataFile:add']"
      >上传数据</el-button>

      <!-- 刷新首页 ---------------------------->
      <el-button
        size="medium"
        type="success"
        icon="el-icon-refresh"
        @click="refresh_home()"

      >刷新首页</el-button>

    </div>

    <el-dialog title="上传数据" :visible.sync="UD_dialog.visible" width="50%">
      <el-form label-width="120px">
        <el-form-item label="数据类型">
          <el-select v-model="UD_dialog.selectedType" placeholder="请选择数据类型" size="large" style="width: 240px" @change="UD_selectType" clearable>
            <el-option v-for="item in UD_dialog.dataType" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <!-- 通用填写  dataName,remark -->
        <el-form-item v-if="UD_dialog.selectedType" v-for="field in UD_dialog.newInputs" :key="field" :label="UD_dialog.dataMap[field]">
          <el-input v-if="UD_dialog.data.hasOwnProperty(field)" v-model="UD_dialog.data[field]" :disabled="UD_dialog.uploadExcelVisible||UD_dialog.uploadSupplementVisible"    placeholder="请输入内容"/>
        </el-form-item>

        <!-- 数据类型为  标准excel时-------------------------------------------->
        <el-form-item v-if="UD_dialog.selectedType=== '标准Excel文件'" label="下载模板">
          <el-button type="small" @click="UD_downloadExcelTemplate">下载模板</el-button>
        </el-form-item>
        <el-form-item v-if="UD_dialog.selectedType === '标准Excel文件'" label="文件" prop="file">
            <el-button v-if="!UD_dialog.uploadExcelVisible" @click="UD_excelUpload" size="mini" type="success">新增(确定参数)</el-button>
          <upload-excel  v-if="UD_dialog.uploadExcelVisible" :upload-data="UD_dialog.getUploadData('excel')"></upload-excel>
        </el-form-item>


        <!-- 数据类型为  指标补充文件时-------------------------------------------->
        <!-- 选择标准号-->
        <el-form-item v-if="UD_dialog.selectedType==='指标补充文件'" label="标准号">
          <el-select v-model="UD_dialog.data['standardCode']" placeholder="请选择标准号" :disabled="UD_dialog.uploadSupplementVisible"  size="large" style="width: 240px" clearable
                     filterable :remote="true" :remote-method="filterStandardCode" :loading="UD_dialog.loadingFilter">
            <el-option v-for="item in UD_dialog.filteredCodes" :key="item" :label="item" :value="item"/>
          </el-select>
        </el-form-item>
        <!-- 新增补充文件 -->
        <el-form-item v-if="UD_dialog.selectedType==='指标补充文件'" label="新增补充文件" >
          <el-button size="small" type="success" icon="el-icon-plus"  @click="UD_supplementUpload">确定参数</el-button>
          <!-- 填写完相应信息后展示 上传 -->
          <el-form-item v-if="UD_dialog.uploadSupplementVisible">
            <div style="max-height: 300px;  overflow-y: auto;" >
              <el-row v-for="(row, index) in this.UD_dialog.supplementRows" :key="index">
                <el-col :span="8">
                  <strong >指标:</strong>
                  <el-form-item>
                    <el-select v-model="row.indicator" placeholder="请选择指标" size="large" style="width: 120px" clearable>
                      <el-option v-for="item in UD_dialog.indicatorList" :key="item" :label="item" :value="item"/>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <strong>选择并上传补充性文件:</strong>
                  <upload-supplement v-if="row.indicator" :upload-data="UD_dialog.getUploadData(row.indicator)"> 选择文件并上传</upload-supplement>
                </el-col>
              </el-row>
            </div>
          </el-form-item>
        </el-form-item>


      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="UD_cancel">取 消</el-button>
      <el-button type="primary" @click="UD_refresh">刷新 数据</el-button>
    </span>
    </el-dialog>

    <!-- 修改数据- Excel ---------------------------->
    <el-dialog title="修改数据(指标得分Excel)" :visible.sync="updateDataDialog.visible_excel" width="500px">
      <el-form label-width="80px" label-position="left">
        <el-form-item label="修改备注: " v-if="updateDataDialog.row && updateDataDialog.row.remark !== undefined">
          <el-input v-model="updateDataDialog.row.remark" :placeholder="'请输入备注'" style="text-align: left;"></el-input>
        </el-form-item>
      </el-form>

      <update-excel :title="getExcelFileName()" :upload-data="this.updateDataDialog.data_excel" :can-upload="true"></update-excel>
      <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="refreshUpdateDataFile('excel')"  >刷新 数据</el-button>
          </span>
    </el-dialog>

    <!-- 修改数据- 补充性文件supplement ---------------------------->
    <el-dialog title="修改数据(补充性文件)" :visible.sync="updateDataDialog.visible_supplement" >
      <el-form label-width="120px" >
        <el-form-item label="说明">
          <span>
            <strong>数据名称:</strong> {{ updateDataDialog.data_supplement.dataName }}
            <span class="spacer"></span>
            <strong>标准号:</strong> {{ updateDataDialog.data_supplement.standardCode }}
          </span>
        </el-form-item>
        <div style="max-height: 500px;  overflow-y: auto; overflow-x: auto"  >
          <el-form-item label="备注" v-if="updateDataDialog.row && updateDataDialog.row.remark !== undefined">
            <el-input v-model="updateDataDialog.row.remark" :placeholder="'请输入备注'" style="text-align: left;"></el-input>
          </el-form-item>

           <el-form-item v-for="(urlList, key) in updateDataDialog.data_supplement.filesPath" :key="key" :label="key">
            <el-row >
              <el-col :span="6" v-for="(url,index) in urlList" :key="index">
                <update-supplement  :can-upload="true" :title="getSupplementName(url)" :upload-data="{dataName:updateDataDialog.data_supplement.dataName,previousUrl:url,indicator:key}">
                </update-supplement>
              </el-col>
            </el-row>
           </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="refreshUpdateDataFile('supplement')" >刷新 数据</el-button>
          </span>
    </el-dialog>



    <!-- 下载数据 ---------------------------->
    <el-dialog title="下载数据" :visible.sync="DL_dialog.visible" >
      <el-form label-width="120px">
        <el-form-item label="说明">
          <span>
            <strong>数据名称:</strong> {{ DL_dialog.data.dataName }}
            <span class="spacer"></span>
            <strong>标准号:</strong> {{ DL_dialog.data.standardCode }}
          </span>
        </el-form-item>
        <div style="max-height: 500px;  overflow-y: auto; overflow-x: auto"  >
          <el-form-item v-for="(urlList, key) in DL_dialog.data.filesPath" :key="key" :label="key">
          <el-row >
            <el-col :span="6" v-for="(url,index) in urlList" :key="index">
              <el-button size="mini" type="text" icon="el-icon-download" @click="DL_downloadFile(url)" :title="getSupplementName(url)">
                <span style="display: inline-block; width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                  {{ getSupplementName(url) }}
                </span>
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        </div>
      </el-form>
    </el-dialog>

    <!-- 审核数据 ---------------------------->
    <el-dialog title="审核数据" :visible.sync="checkReview.visible" >
      <el-form
        ref="form"
        :model="checkReview"
        label-width="80px"
        size="large"
      >
        <el-form-item label="审核" prop="status">
          <el-radio-group v-model="checkReview.status">
            <el-radio :label="0" :disabled="loading">通过</el-radio>
            <el-radio :label="1" :disabled="loading">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="checkReview.remark"
            clearable
            :disabled="loading"
            type="textarea"
            maxlength="100"
            show-word-limit
            placeholder="`请填写备注"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="checkReview.visible = false" :disabled="loading">取 消</el-button>
        <el-button type="primary" @click="submitCheckReview" :disabled="loading">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 数据跟踪 ---------------------------->
    <el-dialog title="数据跟踪" :visible.sync="historyVisible">
      <div>
        <el-timeline>
          <el-timeline-item
            v-for="item in logHistoryList"
            :key="item.id"
            :timestamp="parseTime(item.oper_time)"
            placement="top"
            :color="activeId !== item.id ? '' : '#0bbd87'"
            :id="item.id"
          >
            <el-card style="width: 100%">
              <div
                slot="header"
                class="clearfix flex jc-between ai-center"
                style="width: 100%"
              >
                <div style="flex:1">{{ item.oper_user }} {{item.oper_type}} {{item.data_name}}</div>
              </div>
                <div v-for="(value, key) in item.content" :key="key" class="mb-1">
                <p><strong>{{ key }}:</strong></p>
                <p>
                <el-tag type="info">{{ value.before || '-' }}</el-tag>
                <span class="el-icon-arrow-right" />
                <el-tag type="success">{{ value.after || '-' }}</el-tag>
                </p>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
          <template v-if="!loading && !this.logHistoryList.length">
            <el-empty />
          </template>
        </div>
    </el-dialog>
  </div>

</template>

<script>
import * as echarts from 'echarts';
import {addMenu, delMenu, getMenu, listMenu, updateMenu} from "@/api/system/menu";
import {parseTime} from "@/utils/ruoyi";
import { countSuccessfulLogins } from '@/api/monitor/logininfor';
import {
  countStandardClassification,
  getAllStandardCode,
  getIndicatorSystemCount,
  getStandardEvaluationCount,
} from '@/api/standard/standard';
import { getToken } from "@/utils/auth";
import {
  auditDataFileStatus,
  delDataFile, delDataFileById, deleteDataOperLogByDataName,
  getAllDataFile,
  getDataFileInfo, getDataFileInfoByName, getListDataFile,
  getLogData,
  insertLogData, updateDataFileRemark
} from "@/api/standard/dataFile";
import update from "./datamanager/update.vue";


const statusMap = {
  0: "审核通过",
  1: "未通过审核",
  2: "待审核"
};

const statusTagMap = {
  0: "success",
  1: "danger",
  2: "warning"
};

const historyLabel = {
  'title': '数据名称',
  'status': '审核状态'
}

const labelMap={
  'id':'标准编号',
  'standardCode':'标准号',
  'title':'主标题(标准所属技术领域)',
  'content':'内容主题',
  'part':'分部分号和名称',
  'abstract':'摘要',
  'status':'状态',
  'publicationDate':'发布日期',
  'stage':'所处阶段',
  'edition':'版本号',
  'numberOfPages':'页数',
  'pages':'页数',
  'technicalCommittee':'技术委员会',
  'ics':'国际标准分类号',
  'contribute':'贡献记录'
}

// 不可修改字段
const cannotEdit=['id','standardCode','status','createTime'];

export default {
  name: "Index",
  computed: {
    update() {
      return update
    }
  },
  data() {
    return {
      /** 总标准数 */
      /** 标准总评价次数 */
      standardEvaluateCount: 0,
      /**
       * 修改对话框参数
       */
      updateDataDialog:{
        row:null,

        visible_excel:false,
        data_excel:{
          previousUrl:'',
          dataName:'',
        },

        visible_supplement:false,
        data_supplement:{
          dataName:'',
          standardCode:'',
          filesPath:{},
        },
      },

      /**
       *查询参数
       */
      queryParams: {
        menuName: undefined,
        visible: undefined,
        dictName: undefined,
        dictType: undefined,
        status: undefined,
        pageNum: 1,
        pageSize: 10,
      },
      /**
       * 上传数据对话框
       */
      UD_dialog:{
        loadingFilter:false,
        filteredCodes:[],

        visible:false,
        // 数据类型
        dataType:[{value: '标准Excel文件', label: '标准Excel文件',},
                  {value: '指标补充文件', label: '指标补充文件',},],

        newInputs:[],
        // 英译中
        dataMap:{
          'dataName':'数据名称',
          'remark':'备注',
          'standardCode':'标准号',
          'indicator':'指标',
        },
        // 选择的数据类型
        selectedType:'',
        // 存储写的input内容
        data:{
          'dataName':'',
          'remark':'',
          'standardCode':'',
          'indicator':'',
        },
        uploadData:{
          dataType:'',
          dataName:'',
          remark:'',
          standardCode:'',
          indicator:'',
        },
        getUploadData(indicator){
          this.uploadData.dataType=this.selectedType;
          this.uploadData.dataName=this.data['dataName'];
          this.uploadData.remark=this.data['remark'];
          this.uploadData.standardCode=this.data['standardCode'];
          this.uploadData.indicator=indicator;
          return this.uploadData;
        },
        // Excel 相关参数
        excelForm:{
          excelFile:null,
        },
        uploadExcelVisible:false,
        uploadSupplementVisible:false,

        /**所有标准号*/
        standardCodeList:[],

        /**所有指标*/
        indicatorList:['A11','A12','A13',
                      'B11','B12','B13','B14',
                      'B21','B22','B23','B24',
                      'B31','B32','B33',
                      'B41','B42','B43','B44',],
        /**多个补充性文件(rows)*/
        supplementRows:[],
        /** 是否在一次上传过程中？*/
        isUploadingExcel:false,
        isUploadingSupplement:false,
      },

      /**
       * 下载对话框
       * 这里默认是对 dataType=supplement 的数据进行记录的
       */
      DL_dialog:{
        visible:false,
        data:{
          dataName:'',
          standardCode:'',
          /**
           * 记录 {指标:文件路径} 的映射关系 ，注意，这里的 文件路径为 [] 列表
           */
          filesPath: {},
        },
      },
      // 现有指标体系数
      IndicatorSystemCount:0,
      // 查询数据总条数
      total: 0,
      // 记录成功登录次数
      successfulLoginCount: 0,
      // 标准分类数据
      chartData: [],

      standardchart: null,
      historyLabel,

      // 数据跟踪参数
      historyVisible: false,
      logHistoryList: [],


      statusMap,
      statusTagMap,
      labelMap,
      cannotEdit,
      loading: false,

      // 审核 ----------------------
      checkReview: {
        row: "",
        visible: false,
        status: 1,
        remark: ""
      },
      // 标准数据 ------------------------
      dataList:[],


      // 修改备注
      updateRemarkParams: {
        id: null,
        visible:false,
        remark:null
      },

      // 跟踪 数据操作日志
      oper_type: '',
      data_name: '',
      log_before: {},
      log_after: {},

      // 上传文件
      uploadVisible: false,
      fileForm: {
        fileName: 'hello',
        standardCode: 'ISO 1111111',
        remark: 'test'
      },
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/talkrecord/importAllRecords",
        // 上传的文件列表
        fileList: [],
        // 上传结果
        uploadResult:null
      },

    };
  },
  created() {
    this.resetQuery();
    this.getISCount();
    this.getStandardEvaluationCount();
  },
  async mounted(){
    await this.getStandardClassification();
    await this.fetchSuccessfulLoginCount();
    await this.getStandardCodeList();
  },
  methods: {

    parseTime,
    renderChart(){
      // this.chartDom = document.getElementById('standardchart');
      this.standardchart=echarts.init(this.$refs.standardchart);
      // this.standardchart=echarts.init(this.chartDom);
      this.standardchart.setOption({
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        series: [
          {
            name: "标准数量",
            type: "pie",
            center: ["50%", "38%"],
            data:this.chartData,
            label: {
              normal: {
                show: true,
                position: "inside", // 显示在内侧
                formatter: '{b}: {d}%' // {b}: 类别名称, {d}: 百分比
              }
            },

            animationEasing: "cubicInOut",
            animationDuration: 1000,
          }
        ]
      });
      window.addEventListener("resize", () => {
        this.standardchart.resize();
      });
    },
    /** 查询标准总评价次数*/
    getStandardEvaluationCount(){
      getStandardEvaluationCount().then(response=>{
        if(response.code===200){
          this.standardEvaluateCount=response.data;
        }else{
          this.$message.error('获取标准总评价次数失败');
        }
      }).catch(error=>{
        this.$message.error('获取标准总评价次数失败',error);
      })
    },

    /** 修改---刷新*/
    refreshUpdateDataFile(type){
      /**
       * 新增 API 实现修改备注
       */
      const id = this.updateDataDialog.row.id;
      const remark = this.updateDataDialog.row.remark;

      updateDataFileRemark(id,remark).then(response=>{
        if(response.code===200){
          this.$message.success('更新成功');
          /** 更新查询*/
          this.getDataList();
          if(type==='excel'){
            this.updateDataDialog.visible_excel=false;
          }else if(type==='supplement'){
            this.updateDataDialog.visible_supplement=false;
          }
        }else{
          this.$message.error('备注更新失败');
        }
      }).catch(error=>{
        this.$message.error('备注更新失败',error);
      })

    },

    /** new --- 修改--- 删除并上传 */
    async handleUpdate(row){
      this.updateDataDialog.row=row;
      if(row.dataType==='excel'){
        this.updateDataDialog.visible_excel=true;
        this.updateDataDialog.data_excel.previousUrl=this.updateDataDialog.row.excelPath;
        this.updateDataDialog.data_excel.dataName=this.updateDataDialog.row.dataName;
      }else if(row.dataType==='supplement'){
        await this.getSupplementInfo(row);
      }
    },

    // 获取数据信息 --- supplement
    async getSupplementInfo(row) {
      try {
        const response = await getDataFileInfo(row.id);

        if (response.code === 200) {
          const data = response.data;// 获取的数据
          this.updateDataDialog.data_supplement.dataName = data.dataName;
          this.updateDataDialog.data_supplement.standardCode = data.standardCode;
          this.updateDataDialog.data_supplement.filesPath = JSON.parse(data.filesPath);
          this.updateDataDialog.visible_supplement=true;
        }
        else {
          this.$message.error('获取数据信息失败');
        }
      } catch (error) {
        console.error('获取数据信息失败', error);
        this.$message.error('获取数据信息失败');
      }
    },




    /** new ----- -数据上传相关 -------------------------------------------------------------------------------------*/
    filterStandardCode(query){
      if (query !== '') {
        this.UD_dialog.loadingFilter = true;
        setTimeout(() => {
          this.UD_dialog.filteredCodes = this.UD_dialog.standardCodeList.filter(code => {
            return code.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
          this.UD_dialog.loadingFilter = false;
        }, 200);
      } else {
        this.UD_dialog.filteredCodes = this.UD_dialog.standardCodeList
      }
    },

    /** 获取所有标准号*/
    async getStandardCodeList(){
      try {
        const response = await getAllStandardCode();
        if (response.code === 200) {
          const list=[];
          for(let i=0;i<response.data.length;i++){
            list.push(response.data[i]);
          }
          this.UD_dialog.standardCodeList=list;
          this.UD_dialog.filteredCodes=list;
        } else {
          this.$message.error('获取标准号失败');
        }
      } catch (error) {
        this.$message.error('获取标准号失败');
      }
    },

    /** 判断数据名称是否可行 */
    async UD_dataNameOK(dataName){
      const jsonData = JSON.stringify({dataName:dataName});
      const response = await getDataFileInfoByName(jsonData);
      if (response.code === 200) {
        if (response.data) {// 已经存在，冲突
          return false;
        } else {
          return true;
        }
      } else {
        this.$message.error('获取数据信息失败');
      }
    },

    async UD_supplementUpload(){
      if (!this.UD_dialog.data['dataName'] ) {
        this.$message.warning('请填写数据名称');
        return;
      }
      if(!this.UD_dialog.isUploadingSupplement){// 上传前的参数判断
        this.UD_dialog.isUploadingSupplement=true;// 在上传，允许多个补充性文件
        const nameIsOk = await this.UD_dataNameOK(this.UD_dialog.data['dataName']);
        if(!nameIsOk){
          this.$message.warning('数据名称已存在，请修改');
          return;
        }
      }

      if(!this.UD_dialog.data['remark']){
        this.$message.warning('请填写备注');
        return;
      }
      if(!this.UD_dialog.data['standardCode'])
      {
        this.$message.warning('请填写标准号');
        return;
      }
      this.UD_dialog.uploadSupplementVisible=true;
      /**  添加新的一行  {指标:文件}*/
      this.UD_dialog.supplementRows.push({
        indicator:'',
      });
    },

    async UD_excelUpload(){
      if (!this.UD_dialog.data['dataName'] ) {
        this.$message.warning('请填写数据名称');
        return;
      }
      const nameIsOk = await this.UD_dataNameOK(this.UD_dialog.data['dataName']);
      if(!nameIsOk){
        this.$message.warning('数据名称已存在，请修改');
        return;
      }
      if(!this.UD_dialog.data['remark']){
        this.$message.warning('请填写备注');
        return;
      }
      this.UD_dialog.uploadExcelVisible=true;
    },

    async UD_selectType(val){
      this.UD_dialog.isUploadingSupplement=false;
      this.UD_dialog.supplementRows=[];

      this.UD_dialog.isUploadingExcel=false;


      this.UD_dialog.selectedType=val;
      this.UD_dialog.uploadExcelVisible=false;
      this.UD_dialog.uploadSupplementVisible=false;
      this.UD_dialog.data={
        'dataName':'',
        'remark':'',
        'standardCode':'',
        'indicator':'',
      };
      if(val==='标准Excel文件') {
        this.UD_dialog.newInputs = ['dataName', 'remark'];
      } else if(val==='指标补充文件'){
        this.UD_dialog.newInputs = ['dataName', 'remark'];
        /**
         * 获取所有标准号
         */
        await this.getStandardCodeList();
      }else if(val===''){
        this.UD_dialog.newInputs=[];
      }

    },
    UD_cancel(){
      this.UD_dialog.visible = false;
      this.UD_selectType('');
    },
    // 下载Excel 模板
    UD_downloadExcelTemplate(){
      const url = 'https://localhost:8080/profile/upload/standard_excel_template.xlsx';
      this.$download.resource(url, false);
    },

    /** new --- 文件上传 */
    clickUpload(){
      this.UD_dialog.visible=true;
    },
    /** 文件提交处理 默认已经提交了，这里就是刷新*/
    UD_refresh() {
      this.UD_cancel();
      this.getDataList();
    },

    /** new --- 数据下载  ----------------------------------------------------------------------------------
     *  这里要判断 数据是 excel / supplement
     */
    getExcelFileName(){
      const url = this.updateDataDialog.data_excel.previousUrl;
      return url.substring(url.lastIndexOf('/') + 1);
    },

    /** 获取 补充性文件名称  */
    getSupplementName(url){
      /** 获取文件名 */
      return url.substring(url.lastIndexOf('/') + 1);
    },

    async handleDownload(row) {
      try {
        const response = await getDataFileInfo(row.id);
        if (response.code === 200) {
          const data = response.data;// 获取的数据
          if (data.dataType === 'excel') {// excel类型时，直接返回下载数据即可
            const url = data.excelPath;
            this.$download.resource(url, false);
          } else if (data.dataType === 'supplement') {
            this.DL_dialog.data.dataName = data.dataName;
            this.DL_dialog.data.standardCode = data.standardCode;
            this.DL_dialog.data.filesPath = JSON.parse(data.filesPath);
            this.DL_dialog.visible = true;
          }
        } else {
          this.$message.error('下载失败');
        }
      } catch (error) {
        console.error('下载失败', error);
        this.$message.error('下载失败');
      }
    },
    /** 下载  excel类型数据(指标得分) */
    DL_downloadFile(url){
      this.$download.resource(url, false);
    },

    /** new --- 插入数据操作日志 */
    insertLog(){
      const operUser=this.$store.state.user.name;
      const content = {};
      // 遍历 log_before
      for (const [key, beforeValue] of Object.entries(this.log_before)) {
        // log_after 有相同的键
        if (key in this.log_after) {
          content[key] = {
            'before': beforeValue,
            'after': this.log_after[key]
          };
        }
      }
      // 转换为 JSON 字符串
      const contentString = JSON.stringify(content);

      const data={
        operType:this.oper_type,
        dataName:this.data_name,
        content:contentString,
        operUser:operUser,
      };
      insertLogData(data).then(response=>{
        if(response.code===200){
          this.$message.success('跟踪成功');
        }else{
          this.$message.error('跟踪失败');
        }
      }).catch(error=>{
        this.$message.error('跟踪失败');
      })
    },

    /** new --- 删除数据操作日志 by dataName */
    deleteLogByDataName(dataName){
      deleteDataOperLogByDataName(dataName).then(response=>{
        if(response.code===200){
          this.$message.success('跟踪数据删除成功');
        }else{
          this.$message.error('跟踪数据删除失败');
        }
      }).catch(error=>{
        console.error('跟踪数据删除失败',error);
        this.$message.error('跟踪数据删除失败');
      })
    },


    /** new --- 跟踪数据 */
    handlePath(row){
      getLogData(row.dataName).then(response=>{
        if(response.code===200){
          this.logHistoryList=response.data.map((item)=>({
            id:item.id,
            oper_type:item.operType,
            data_name:item.dataName,
            content:JSON.parse(item.content),
            oper_user:item.operUser,
            oper_time:item.operTime,
          }));
          this.historyVisible = true;
        }else{
          this.$message.error('获取数据跟踪失败');
        }
      }).catch(error=>{
        console.error('获取数据跟踪失败',error);
        this.$message.error('获取数据跟踪失败');
      })
    },

    /** new --- 删除数据 */
    async handleDelete(row) {
      await this.$modal.confirm('是否确认删除名称为 "' + row.dataName + '" 的数据项？');
      /** 删除数据库表及服务器文件 */
      const response = await delDataFileById(row.id);
      if (response.code === 200) {
        this.$message.success('删除成功');
      } else {
        this.$message.error('删除失败');
      }
      /** 删除数据操作日志 */
      this.deleteLogByDataName(row.dataName);
      this.UD_refresh();
    },

    /** new --- 审核数据状态 */
    handleCheck(row) {
      if(row.status!=='2'){
        this.$message.warning('该数据已完成审核');
        return;
      }

      this.checkReview.status = row.status;
      this.checkReview.remark = row.remark;
      this.checkReview.visible = true;
      this.checkReview.row = row;

      // 记录修改前的数据
      this.data_name=row.dataName;
      this.oper_type='审核';
      this.log_before={
        "状态":statusMap[row.status],
        "备注":row.remark
      };
    },
    submitCheckReview() {
      this.loading = true;
      const id = this.checkReview.row.id;
      const newStatus = this.checkReview.status.toString();
      const remark = this.checkReview.remark;
      auditDataFileStatus(id, newStatus, remark).then(response => {
        this.loading = false;
        if (response.code === 200) {
          /**
           * 插入数据操作日志------------------
           */
          this.log_after={
            "状态":statusMap[newStatus],
            "备注":remark
          };
          this.insertLog();


          this.$message.success("审核成功");
          this.checkReview.visible = false;
          this.getDataList();
        } else {
          this.$message.error("审核失败");
        }
      });
    },


    /** 刷新首页*/
    async refresh_home(){
      await this.getStandardClassification();
      await this.fetchSuccessfulLoginCount();
      await this.getStandardCodeList();
      this.resetQuery();
      this.getISCount();
      this.getStandardEvaluationCount();
    },

    /** new --条件查询 **/
    // 重置按钮 ---- 重置表单+查
    resetQuery() {
      this.queryParams.pageNum = 1;
      this.getDataList();
    },
    // 查询按钮
    getDataList(){
      this.loading = true;
      getListDataFile(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取现有指标体系数*/
    getISCount(){
      getIndicatorSystemCount().then(response=>{
        this.IndicatorSystemCount=response.data;
      }).catch(error=>{
        this.$message.error('获取指标体系数失败',error);
      })
    },

    /** new --统计标准分类 **/
    async getStandardClassification(){
      try {
        const response=  await countStandardClassification();
        if (response.code === 200 && response.data) {
          const data = response.data;
          // 转换为数组
          this.chartData = Object.entries(data).map(([key, value]) => ({
            name: key,
            value: value
          }));
          // 重新渲染图表
          this.renderChart();
        } else {
          this.$message.error('获取标准分类失败');
        }
      } catch (error) {
        this.$message.error('获取标准分类失败');
      }
    },

    /** new --获取成功登录次数/访问次数 **/
    async fetchSuccessfulLoginCount() {
      try {
        const response = await countSuccessfulLogins()
        if (response.code === 200) this.successfulLoginCount = response.data;
        else this.$message.error('获取成功登录次数失败');
      } catch (error) {
        this.$message.error('获取成功登录次数失败',error);
      }
    },


    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      listMenu(this.queryParams).then(response => {
        this.menuList = this.handleTree(response.data, "menuId");
        this.loading = false;
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
      };
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listMenu().then(response => {
        this.menuOptions = [];
        const menu = { menuId: 0, menuName: '主类目', children: [] };
        menu.children = this.handleTree(response.data, "menuId");
        this.menuOptions.push(menu);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        menuId: undefined,
        parentId: 0,
        menuName: undefined,
        icon: undefined,
        menuType: "M",
        orderNum: undefined,
        isFrame: "1",
        isCache: "0",
        visible: "0",
        status: "0"
      };
      this.resetForm("form");
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },

    /** 修改按钮操作 */
    handleUpdate2(row) {
      this.reset();
      this.getTreeselect();
      getMenu(row.id).then(response => {
        this.form = response.data;
        this.isUpdateDialogOpen2 = true;
        this.title = "修改菜单";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.menuId != undefined) {
            updateMenu(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMenu(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },


  }
};
</script>

<style scoped lang="scss">

.statistic-box {
  display: flex;
  align-items: center;
  border: 2px solid #5c7bd9;
  border-top: 10px solid #5c7bd9;
  border-radius: 10px;
  padding: 10px;
  height: 200px;
  margin-right: 20px;
}

.icon {
  color: #5c7bd9;
  margin-right: 10px;
  /* 根据实际图标大小调整 */
}

.content .title {
  font-size: 30px;
  color: #5c7bd9;
  padding: 10px;
  text-align: left;
}

.content .number {
  font-size: 50px;
  font-weight: bold;
  color: #333;
  text-align: right;
}

.el-upload-dragger {
  width: 100% !important;
  height: 200px;
}

.el-upload__text{
  width: 100% !important;

}
.spacer{
  margin: 0 20px;
}
</style>

